package pfq.demo.rx;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import java.util.concurrent.TimeUnit;

import androidx.appcompat.app.AppCompatActivity;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import pfq.demo.R;

/**
 * 演示使用RxJava实现轮询功能
 */
public class PollingActivity extends AppCompatActivity {


    private TextView mPollingStatusTextView;

    private CompositeDisposable mCompositeDisposable;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rx_polling);

        mPollingStatusTextView = (TextView) findViewById(R.id.pollingStatusTextView);

        findViewById(R.id.startPollingButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startPolling();
            }
        });


        mCompositeDisposable = new CompositeDisposable();
    }

    /**
     * 开始轮询
     */
    private void startPolling() {

        // 被观察者
        Observable<Long> observable = Observable.intervalRange(0, 5, 0, 3000, TimeUnit.MILLISECONDS).take(5).doOnNext(new Consumer<Long>() {
            @Override
            public void accept(Long aLong) throws Exception {
                doWork();
            }
        });

        // 观察者
        DisposableObserver<Long> disposableObserver = new DisposableObserver<Long>() {
            @Override
            public void onNext(Long aLong) {
                mPollingStatusTextView.setText("轮询次数：" + aLong);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        };

        // 被观察者订阅观察者
        observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(disposableObserver);
        mCompositeDisposable.add(disposableObserver);
    }

    /**
     * 模拟网络耗时
     */
    private void doWork() {
        long workTime = (long) (Math.random() * 500) + 500;
        try {
            Thread.sleep(workTime);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCompositeDisposable.clear();
    }
}
